from django.shortcuts import render,redirect
from django.http.response import HttpResponse
import datetime
from sm_system.models import *
COOKIE_NAME = 'sm_session'

#总部 hq
def hq_index(request):
    customers = CustomerInfo.objects.all()
    context={'customers':customers}
    return render(request,'customer/hq_customer.html',context)

def hq_update(request,id):
    customer=CustomerInfo.objects.get(id=id)
    context={"customer":customer}
    return render(request,'customer/hq_customerUpdate.html',context)

def hq_update_form(request):
    if request.POST:
        oldid=request.POST['oldid']
        customer=CustomerInfo.objects.get(id=oldid)
        customer.id=request.POST['id']
        customer.name=request.POST['name']
        customer.contact=request.POST['contact']
        customer.save()
        return redirect('/customer/hq-index/')
    else:
        return redirect('/customer/hq-index/')

#顾客消费记录
def hq_consumercsp(request,customerid):
    csp_info=[]
    sales = Salesrecord.objects.filter(customer_id=customerid)
    for sale in sales:
        commodity = CommodityInfo.objects.get(id=sale.commodity_id)
        info = {
            "commodity_id": commodity.id,
            "commodity_name": commodity.name,
            "commodity_price": commodity.sell_price,
            "date":sale.date
        }
        csp_info.append(info)

    context={"csp_info":csp_info}
    return render(request,'customer/hq_customercsp.html',context)


# 分部
def index(request):
    supermarket_id=str(request.COOKIES.get(COOKIE_NAME))[0:4]
    customers = CustomerInfo.objects.filter(supermarket_id=supermarket_id)
    context={'customers':customers}
    return render(request,'customer/customer.html',context)


def update(request,id):
    customer=CustomerInfo.objects.get(id=id)
    context={"customer":customer}
    return render(request,'customer/customerUpdate.html',context)

def update_form(request):
    if request.POST:
        oldid=request.POST['oldid']
        customer=CustomerInfo.objects.get(id=oldid)
        customer.id=request.POST['id']
        customer.name=request.POST['name']
        customer.contact=request.POST['contact']
        customer.save()
        return redirect('/customer/index/')
    else:
        return redirect('/customer/index/')

def add(request):
    return render(request,'customer/customerAdd.html')

def add_form(request):
    if request.POST:
        supermarket_id=str(request.COOKIES.get(COOKIE_NAME))[0:4]
        customer=CustomerInfo()
        customer.id=request.POST['id']
        customer.name=request.POST['name']
        customer.contact=request.POST['contact']
        customer.reg_date=datetime.date.today()
        customer.supermarket_id=supermarket_id
        customer.save()
        return redirect('/customer/index/')
    else:
        return redirect('/customer/index/')



